package oct2013;

import java.util.ArrayList;

/**
 * @author Yinzi Chen
 * @date Nov 7, 2013
 */
public class RestoreIPAddresses {
    ArrayList<String> res;
    int n;
    int[] buf;
    String s;

    public ArrayList<String> restoreIpAddresses(String s) {
        res = new ArrayList<String>();
        this.s = s;
        n = s.length();
        buf = new int[4];
        dfs(0, 0);
        return res;
    }

    void dfs(int j, int dep) {
        if (dep == 4 && j == n) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 4; ++i) {
                sb.append(buf[i]);
                sb.append('.');
            }
            sb.deleteCharAt(sb.length() - 1);
            res.add(sb.toString());
            return;
        }
        if (j == n)
            return;
        if (s.charAt(j) == '0') {
            buf[dep] = 0;
            dfs(j + 1, dep + 1);
        } else {
            int v = 0;
            for (; j < n; ++j) {
                v *= 10;
                v += s.charAt(j) - '0';
                if (v > 255)
                    return;
                dfs(j + 1, dep + 1);
            }
        }
    }
}
